<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mecoupon extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function dbindex()
    {
        return $this->renderQrCode('5GT5FC');
    }
    
    public function getEcouponDB($number,$offset)
    {
        $limit = $offset ? intval($offset) : '0';
        $sql  = '';
        $sql1 = "SELECT u.username, e.id, e.title, e.active,e.amount,e.img_thumbnail, e.amount_available, e.admin_id, e.created, e.date_user, e.sale_off FROM ecoupon AS e INNER JOIN `user` AS u ON e.admin_id = u.id WHERE 1=1 ";
        $sql2 = "SELECT e.id FROM ecoupon AS e INNER JOIN `user` AS u ON e.admin_id = u.id WHERE 1=1 ";
        
        $key = $this->getParamString('keyword');
        if(!in_array($key, array(null, '', '0')))
        {
            $sql .= " AND (e.title like '%%".$key."%%' OR ";
            $sql .= " e.code_coupon like '%%".$key."%%' OR ";
            $sql .= " e.title_ascii like '%%".$key."%%') ";
        }
        $sql .= "ORDER BY e.id DESC";
        
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql1.$sql.$xdata)->result_object();
        
        $count = $this->db->query($sql2.$sql)->num_rows();
        return array('data' => $xs, 'count' => $count);   
    }
    
    public function renderQrCode($data, $path)
    {
        $this->load->library('ciqrcode');

        $time_folder = date('Ym');
        $path_mk = 'data/images/'.$path.$time_folder;
        @mkdir(PROJECT_PATH.'/'.$path_mk, 0777);
        $file = 'images/'.$path.$time_folder.'/'.date('Ymd').'-'.time().'.jpg';
        $params['data'] = $data;
        $params['level'] = 'H';
        $params['size'] = 30;
        $params['savename'] = PROJECT_PATH.'/data/'.$file;
        //die(print_r($params));
        $this->ciqrcode->generate($params);
        return $file;
    }
    
    
    private function _renderEcoupon($amount)
    {
        return $this->generateCode($amount);
    }
    
    public function renderEcouponOne()
    {
        $coupon = $this->_renderEcoupon(6);
        $coupon_qr = $this->_renderEcoupon(12);
        return $this->getRenderEcoupon($coupon, $coupon_qr);
    }
    
    private function getRenderEcoupon($ecoupon, $ecoupon_qr)
    {
        $check = $this->db->query('SELECT id FROM ecoupon WHERE code_coupon = "'.$ecoupon.'" AND code_coupon_qrcode = "'.$ecoupon_qr.'"')->num_rows();
        if($check == 1)
        {
            $coupon = $this->_renderEcoupon(5);
            $coupon_qr = $this->_renderEcoupon(12);
            return $this->getRenderEcoupon($ecoupon, $coupon_qr);
        }else{
            return (object)array('coupon' => $ecoupon, 'coupon_qr' => $ecoupon_qr);
        }
    }
    
    public function checkCode($code_post)
    {
        $check = $this->db->query('SELECT id FROM ecoupon WHERE code_coupon = "'.$code_post.'"')->num_rows();
        if($check == 1)
        {
            $coupon = $this->_renderEcoupon(5);
            return $this->checkCode($ecoupon);
        }else{
            return $this->checkCode($ecoupon);
        }
    }
    
    public function dbgetrestaurant()
    {
        $sql = "SELECT id,name FROM restaurant ORDER BY name ASC";
        $data = $this->db->query($sql)->result_array();
        return $data;
    }
    
    public function addEcouponDB($data, $arr_restaurant, $admin_id, $code, $code_qr, $img_qrcode, $baseurl,$img_thumbnail)
    {
        
        $date = date('Ymd').'-'.time().'-'.rand(1,100).'.jpg';
        $name_folder = date('Ym');
        @mkdir(PROJECT_PATH.'/data/images/qrcode/'.$name_folder, 0301);
        $amount_available = $this->getParamInt('amount_available');
        $amount = $this->getParamInt('amount');
        if(!in_array($amount_available, array(null, '')))
        {
            $amount_available = $amount_available;
        }else{
            $amount_available = 0;
        }
        
        $data['title']              = $this->getParamString('title');
        $data['title_ascii']        = $this->get_ascii($data['title']);
        $data['sale_off']           = $this->getParamString('sale_off');
        $data['amount']             = $amount;
//        $data['amount_available']   = (int)$amount_available;
        $data['amount_available']   = 0;
        $data['date_user']          = strtotime(str_replace('/', '-', $this->getParamString('date_user')));
        //$data['point'] = $this->getParamString('point');
        $data['content_sale_off']   = $this->getParamString('brief');
        $data['content']            = '<div style="font-family: OpenSans;">'.htmlspecialchars_decode($this->getParamString('content')).'</div>';
        $data['active']             = $this->getParamInt('content');
        $data['created']            = date('Y-m-d H:i:s');
        $data['admin_id']           = $admin_id;
        $data['code_coupon']        = $code;
        $data['code_coupon_qrcode'] = $code_qr;
        $data['active']             = $this->getParamInt('active');
        $data['condition']          = $this->getParamString('condition') ? $this->getParamString('condition') : 0;
        $data['img_qrcode'] = $img_qrcode;
		$data['img_thumbnail'] = $img_thumbnail;
        $data['subject_email'] = $this->getParamString('subject_email');
        $data['note_email'] = htmlspecialchars_decode($this->getParamString('note_email'));
        $this->db->insert('ecoupon', $data);
        $id = $this->db->insert_id(); 
		$max_ccp = (int)$this->db->query('SELECT code_coupon FROM ecoupon_user ORDER BY id DESC LIMIT 1 ')->row()->code_coupon;
		if( in_array($max_ccp,array('',null))){
			$max_ccp = (int)0;
		}
		for( $i = 1; $i<= $amount;$i++ ){
			$code_cp = $this->hack_meme($max_ccp + $i); //die('-'.$code_cp);
                        $arr_code[]=$code_cp;
			$this->db->insert('ecoupon_user', array('coupon_id' => $id, 'active' => 0, 'code_coupon' =>  $code_cp , 'admin_id' => $this->session->userdata('admin_id')));
		}
        if($id > 0)
        {
            if($arr_restaurant != 0)
            {
                $restaurants = $arr_restaurant;
                foreach($restaurants AS $le=>$el)
                {
                    $c_cate = array('id_restaurant' => $el, 'id_ecoupon' => $id, 'admin_id' => $admin_id, 'created' => date('Y-m-d H:i:s'));
                    $this->db->insert('ecoupon_key', $c_cate);
                }
//                return 200;
            }    
        } 
        $this->addEcouponOther($data, $arr_restaurant, $admin_id, $code, $code_qr, $img_qrcode, $baseurl,$img_thumbnail,$id,$arr_code);
        return 200;
    }
    
	public function hack_meme($max_ccp){
		$data = (int)$max_ccp; //return 1; 
		$data_ = (string)$data; 
		$len = strlen($data_);
		$len_ = 6 - (int)$len;
		$meme = '';
		for( $j = 0 ;$j < $len_ ;$j++ ){
			$meme .= '0';
		}
		$data_ = $meme.$data_;
		return $data_;
	}
    
    public function editEcouponDB($data, $arr_restaurant, $admin_id, $baseurl, $id,$img_thumbnail)
    {
        $amount_available = $this->getParamInt('amount_available');
        $amount = $this->getParamInt('amount');
        if(!in_array($amount_available, array(null, '', '0')))
        {
            $amount_available = $amount_available;
        }else{
            $amount_available = 0;
        }
        
        $data['title']              = $this->getParamString('title');
        $data['title_ascii']        = $this->get_ascii($data['title']);
        $data['sale_off']           = $this->getParamString('sale_off');
        //Nếu  amount_avalable lớn hơn không thì mình mới thêm amount mới vào
        $ecouponOld=$this->db->query("SELECT * FROM ecoupon WHERE id = '$id'")->row();
        
        $amountAvailableOld=$ecouponOld->amount_available;
        if($amountAvailableOld == 0)
        {
            $data['amount']             = $amount;
        }
//        $data['amount_available']   = $amount_available;
        $data['date_user']          = strtotime(str_replace('/', '-', $this->getParamString('date_user')));
        //$data['point'] = $this->getParamString('point');
        $data['content_sale_off']   = $this->getParamString('brief');
        $data['content']            = '<div style="font-family: OpenSans;">'.htmlspecialchars_decode($this->getParamString('content')).'</div>';
        $data['active']             = $this->getParamInt('content');
        $data['created']            = date('Y-m-d H:i:s');
        $data['admin_id']           = $admin_id;
        $data['active']             = $this->getParamInt('active');
        $data['condition']          = $this->getParamString('condition') ? $this->getParamString('condition') : 0;
        $data['img_thumbnail'] = $img_thumbnail;
        $data['subject_email'] = $this->getParamString('subject_email');
        $data['note_email'] = htmlspecialchars_decode($this->getParamString('note_email'));
        $this->db->update('ecoupon', $data, 'id = '.$id);
        //check(amount_available) >0 ko làm j,==0 thì nếu số lượng thay đổi thì delete rồi insert
        if($amountAvailableOld == 0 && $amount != $ecouponOld->amount )
        {
            $this->db->delete('ecoupon_user', array('coupon_id' => $id));
            $max_ccp = (int)$this->db->query('SELECT code_coupon FROM ecoupon_user ORDER BY id DESC LIMIT 1 ')->row()->code_coupon;
            if( in_array($max_ccp,array('',null))){
                    $max_ccp = (int)0;
            }
            for( $i = 1; $i<= $amount;$i++ ){
                    $code_cp = $this->hack_meme($max_ccp + $i); //die('-'.$code_cp);
                    $this->db->insert('ecoupon_user', array('coupon_id' => $id, 'active' => 0, 'code_coupon' =>  $code_cp , 'admin_id' => $this->session->userdata('admin_id')));
            }
             
        }
        if($data['type_sl'] == 1)
        {    
            $this->dbeditEcouponkey($id,$arr_restaurant,$admin_id);
        }else{
            $this->dbdeleteEcouponkey($id,$arr_restaurant,$admin_id);
        }
        $this->editEcouponOtherDB($data, $arr_restaurant, $admin_id, $baseurl, $id, $img_thumbnail);
        return 200;
    }
    
    public function editEcouponOtherDB($data, $arr_restaurant, $admin_id, $baseurl, $id,$img_thumbnail)
    {
        $this->db_b = $this->load->database('wicard', TRUE);
        $result=$this->db_b->query("SELECT id FROM ecoupon WHERE id_copy = '$id' ");
        if($result->num_rows() == 0 )
        {
            $editCoupon=$this->db->query("SELECT * FROM ecoupon WHERE id = '$id'")->row();
            $code=$editCoupon->code_coupon;
            $code_qr=$editCoupon->code_coupon_qrcode;
            $img_qrcode=$editCoupon->img_qrcode;
//            var_dump($data, $arr_restaurant, $admin_id, $code, $code_qr, $img_qrcode, $baseurl,$img_thumbnail,$id,0);die;
            $this->addEcouponOther($data, $arr_restaurant, $admin_id, $code, $code_qr, $img_qrcode, $baseurl,$img_thumbnail,$id,0);
            $result=$this->db_b->query("SELECT id FROM ecoupon WHERE id_copy = '$id' ");  
            $id=$result->row()->id;
        }
        else {
             $id=$result->row()->id;
        }
        $amount_available = $this->getParamInt('amount_available');
        $amount = $this->getParamInt('amount');
        if(!in_array($amount_available, array(null, '', '0')))
        {
            $amount_available = $amount_available;
        }else{
            $amount_available = 0;
        }
        
        $data['title']              = $this->getParamString('title');
        $data['title_ascii']        = $this->get_ascii($data['title']);
        $data['sale_off']           = $this->getParamString('sale_off');
        //Nếu  amount_avalable lớn hơn không thì mình mới thêm amount mới vào
        $ecouponOld=$this->db_b->query("SELECT * FROM ecoupon WHERE id = '$id'")->row();
        $amountAvailableOld=$ecouponOld->amount_available;
        if($amountAvailableOld == 0)
        {
            $data['amount']             = $amount;
        }
//        $data['amount_available']   = $amount_available;
        $data['date_user']          = strtotime(str_replace('/', '-', $this->getParamString('date_user')));
        //$data['point'] = $this->getParamString('point');
        $data['content_sale_off']   = $this->getParamString('brief');
        $data['content']            = '<div style="font-family: OpenSans;">'.htmlspecialchars_decode($this->getParamString('content')).'</div>';
        $data['active']             = $this->getParamInt('content');
        $data['created']            = date('Y-m-d H:i:s');
        $data['admin_id']           = $admin_id;
        $data['active']             = $this->getParamInt('active');
        $data['condition']          = $this->getParamString('condition') ? $this->getParamString('condition') : 0;
        $data['img_thumbnail'] = $img_thumbnail;
        $data['subject_email'] = $this->getParamString('subject_email');
        $data['note_email'] = htmlspecialchars_decode($this->getParamString('note_email'));
        $this->db_b->update('ecoupon', $data, 'id = '.$id);
         //check(amount_available) >0 ko làm j,==0 thì nếu số lượng thay đổi thì delete rồi insert
        if($amountAvailableOld == 0 && $amount != $ecouponOld->amount )
        {
            $this->db_b->delete('ecoupon_user', array('coupon_id' => $id));
            $max_ccp = (int)$this->db_b->query('SELECT code_coupon FROM ecoupon_user ORDER BY id DESC LIMIT 1 ')->row()->code_coupon;
            if( in_array($max_ccp,array('',null))){
                    $max_ccp = (int)0;
            }
            for( $i = 1; $i<= $amount;$i++ ){
                    $code_cp = $this->hack_meme($max_ccp + $i); //die('-'.$code_cp);
                    $arrayInsert=array(
                        'coupon_id' => $id, 
                        'active' => 0, 
                        'code_coupon'  =>  $code_cp , 
                        'admin_id'     =>  $this->session->userdata('admin_id'),
                        'code_coupon_copy' => 1
                    );
                    $a=$this->db_b->insert('ecoupon_user', $arrayInsert);
            }
             
        }
        if($data['type_sl'] == 1) //ko phải tất cả nhà hàng
        {    
            $this->db_b->delete('ecoupon_key', array('id_ecoupon' => $id));
            //convert nhà hàng
            $restaurants=$arr_restaurant;
            $restaurants=$this->db_b->query("SELECT id FROM restaurant WHERE id_copy IN ('" . (is_array($restaurants) ? implode("','", $restaurants) : $restaurants) . "')")->result_object();
            foreach($restaurants AS $value)
            {
                $data = array(
                    'id_restaurant' => $value->id,
                    'id_ecoupon' => $id,
                    'admin_id' => $admin_id,
                    'created' => date("Y-m-d H:i:s")
                );
                $this->db_b->insert('ecoupon_key', $data);
            }
        }else{ //tất cả nhà hàng
            $this->db_b->delete('ecoupon_key', array('id_ecoupon' => $id));
            $restaurants=$this->db_b->query('SELECT id FROM restaurant WHERE id_copy IS NOT NULL ') ->result_object();
            foreach ($restaurants AS $le => $el)
            {
                $c_cate = array('id_restaurant' => $el->id, 'id_ecoupon' => $id, 'admin_id' => $admin_id, 'created' => date('Y-m-d H:i:s'));
                $this->db_b->insert('ecoupon_key', $c_cate);
            }
        }
        copy(PROJECT_PATH.'/data/'.$img_thumbnail,PATH_W.'/data/'.$img_thumbnail);
        return 200;
    }
    
    public function deleteEcouponDB($id)
    {
        $data = $this->db->query("SELECT img_qrcode FROM ecoupon WHERE id IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')")->result_object();
        foreach($data AS $el=>$le)
        {
            @unlink(PROJECT_PATH.'/data/'.$le->img_qrcode);    
        }
        $this->db->query("DELETE FROM ecoupon WHERE id IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
        $this->db->query("DELETE FROM ecoupon_user WHERE coupon_id IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
        $this->db->query("DELETE FROM ecoupon_key WHERE id_ecoupon IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
        $this->db->query("DELETE FROM ecoupon_review WHERE coupon_id IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
        $this->deleteEcouponOtherDB($id,$le->img_qrcode);
        return 200;
    }
    public function deleteEcouponOtherDB($id,$img)
    {
//        $stringImg=  $img;
//        $code='12345';
//        $signature=hash_hmac("sha256", $code, 'khoaitayran201291@gmail.com:skype:tungnt2o12');
//        $url='http://localhost/wicard/api/delete-img?img='.urlencode($stringImg).'&code='.$code.'&signature='.$signature;
//        $status=file_get_contents($url);
        $this->db_b = $this->load->database('wicard', TRUE);
//        $coupon_w=$this->db_b->query("SELECT id FROM ecoupon WHERE id_copy IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')")->result_object();
//        foreach ($coupon_w as $value)
//        {
//            $arrayId[]=$value->id;
//        }
        $this->db_b->query("UPDATE ecoupon SET delete_status=1 WHERE id_copy IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
//        $this->db_b->query("DELETE FROM ecoupon WHERE id_copy IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
//        $this->db->query("DELETE FROM ecoupon_user WHERE coupon_id IN ('" . (is_array( $arrayId) ? implode("','",  $arrayId) :  $arrayId) . "')");
//        $this->db->query("DELETE FROM ecoupon_key WHERE id_ecoupon IN ('" . (is_array( $arrayId) ? implode("','",  $arrayId) :  $arrayId) . "')");
//        $this->db->query("DELETE FROM ecoupon_review WHERE coupon_id IN ('" . (is_array( $arrayId) ? implode("','",  $arrayId) :  $arrayId) . "')");
        return 200;
    }

    
    private function dbeditEcouponkey($id,$restaurant,$admin_id)
    {
        $this->db->delete('ecoupon_key', array('id_ecoupon' => $id));
        foreach($restaurant AS $key=>$value)
        {
            $data = array(
                'id_restaurant' => $value,
                'id_ecoupon' => $id,
                'admin_id' => $admin_id,
                'created' => date("Y-m-d H:i:s")
            );
        
            $this->db->insert('ecoupon_key', $data);
        }
    }
    private function dbdeleteEcouponkey($id,$restaurant,$admin_id)
    {
        $this->db->delete('ecoupon_key', array('id_ecoupon' => $id));
    }
    
    public function getEcounponData($id)
    {
        $data = $this->db->query('SELECT * FROM ecoupon WHERE id = "'.$id.'"')->row_array();
        $data['id_restaurant'] = $this->db->query('SELECT id_restaurant AS id FROM ecoupon_key WHERE id_ecoupon = '.$id)->result_array();
        return $data;
    }
    
    public function getReportList($number,$offset)
    {
        $limit = $offset ? intval($offset) : '0';
        $sql = "SELECT id,title,amount,amount_available,date_user,active FROM ecoupon WHERE 1=1";
        
        $key = $this->getParamString('keyword');
        if(!in_array($key, array(null, '', '0')))
        {
            $sql .= " AND title like '%%".$key."%%'";
        }
        $sql .= " ORDER BY id DESC";
        
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql.$xdata)->result_object();
        
        $count = $this->db->query($sql)->num_rows();
        return array('data' => $xs, 'count' => $count);   
    }
    
    public function getReportThis($number,$offset,$id)
    {
        $limit = $offset ? intval($offset) : '0';
        $sql = "SELECT eu.id,eu.code_coupon,eu.time_use,eu.created,eu.active,m.username FROM ecoupon_user AS eu LEFT JOIN member AS m ON eu.user_id = m.id WHERE coupon_id = ".$id;
        
        //$key = $this->getParamString('keyword');
        //if(!in_array($key, array(null, '', '0')))
        //{
        //    $sql .= " AND title like '%%".$key."%%'";
        //}
        $sql .= " ORDER BY eu.active DESC, eu.id DESC";
        
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql.$xdata)->result_object();
        
        $count = $this->db->query($sql)->num_rows();
        return array('data' => $xs, 'count' => $count);
    }
    
    public function getReportExport($id)
    {
        $sql = "SELECT eu.id,eu.code_coupon,eu.time_use,eu.active,m.username FROM ecoupon_user AS eu LEFT JOIN member AS m ON eu.user_id = m.id WHERE coupon_id = ".$id." ORDER BY eu.active DESC, eu.id DESC";
        $data = $this->db->query($sql)->result_object();
        return $data;
    }
    
    public function getEcouponInfo($id)
    {
        $data = $this->db->query("SELECT * FROM ecoupon WHERE id = ".$id)->row_object();
        $data->used = $this->db->query("SELECT count(id) AS count FROM ecoupon_user WHERE coupon_id = ".$id." AND active = 2")->row_object()->count;
        return $data;
    }
    
    public function addEcouponOther($data, $arr_restaurant, $admin_id, $code, $code_qr, $img_qrcode, $baseurl,$img_thumbnail,$id_copy,$arr_code)
    {
        
        $admin_id=11;
         //Thêm đoạn add vào wicard
        $this->db_b = $this->load->database('wicard', TRUE);
//        $data = $this->db_b->query("SELECT ID,server,port,connections,`limit`,`type` FROM balancing WHERE config IS NOT NULL ORDER BY ID ASC")->result_object();
      
        $date = date('Ymd').'-'.time().'-'.rand(1,100).'.jpg';
        $name_folder = date('Ym');
        @mkdir(PROJECT_PATH.'/data/images/qrcode/'.$name_folder, 0301);
        $amount_available = $this->getParamInt('amount_available');
        $amount = $this->getParamInt('amount');
        if(!in_array($amount_available, array(null, '')))
        {
            $amount_available = $amount_available;
        }else{
            $amount_available = 0;
        }
//        $path_other = 'C:\wamp\www\wicard';
        copy(PROJECT_PATH.'/data/'.$img_thumbnail,PATH_W.'/data/'.$img_thumbnail);
        copy(PROJECT_PATH.'/data/'.$img_qrcode,PATH_W.'/data/'.$img_qrcode);
    $zone = $this->db_b->query("SELECT id FROM zone")->result_array();    
        $data['title']              = $this->getParamString('title');
        $data['title_ascii']        = $this->get_ascii($data['title']);
        $data['sale_off']           = $this->getParamString('sale_off');
        $data['amount']             = $amount;
        $data['amount_available']   = 0;
        $data['date_user']          = strtotime(str_replace('/', '-', $this->getParamString('date_user')));
        //$data['point'] = $this->getParamString('point');
        $data['content_sale_off']   = $this->getParamString('brief');
        $data['content']            = '<div style="font-family: OpenSans;">'.htmlspecialchars_decode($this->getParamString('content')).'</div>';
        $data['active']             = $this->getParamInt('content');
        $data['created']            = date('Y-m-d H:i:s');
    $data['admin_id']           = $admin_id;
        $data['code_coupon']        = $code;
        $data['code_coupon_qrcode'] = $code_qr;
        $data['active']             = $this->getParamInt('active');
        $data['condition']          = $this->getParamString('condition') ? $this->getParamString('condition') : 0;
        $data['img_qrcode'] = $img_qrcode;
        $data['id_copy'] = $id_copy;
    
        
    $data['img_thumbnail'] = $img_thumbnail;
        $data['subject_email'] = $this->getParamString('subject_email');
        $data['note_email'] = htmlspecialchars_decode($this->getParamString('note_email'));
       
        $this->db_b->insert('ecoupon', $data);
        $id = $this->db_b->insert_id(); 
		$max_ccp = (int)$this->db_b->query('SELECT code_coupon FROM ecoupon_user ORDER BY id DESC LIMIT 1 ')->row()->code_coupon;
		if( in_array($max_ccp,array('',null))){
			$max_ccp = (int)0;
		}
		for( $i = 1; $i<= $amount;$i++ ){
			$code_cp = $this->hack_meme($max_ccp + $i); //die('-'.$code_cp);
                        $arrayInsert=array(
                            'coupon_id' => $id, 
                            'active' => 0, 
                            'code_coupon'  =>  $code_cp , 
                            'admin_id'     =>  $this->session->userdata('admin_id'),
                            'code_coupon_copy' => 1
                        );
			$a=$this->db_b->insert('ecoupon_user', $arrayInsert);
		}
        if($id > 0)
        {
            if($arr_restaurant != 0)
            {
                $restaurants = $arr_restaurant;
                //Lấy restaurants bên wicard
                $restaurants=$this->db_b->query("SELECT id FROM restaurant WHERE id_copy IN ('" . (is_array($restaurants) ? implode("','", $restaurants) : $restaurants) . "')")->result_object();
                foreach($restaurants AS $le=>$el)
                {
                    $c_cate = array('id_restaurant' => $el->id, 'id_ecoupon' => $id, 'admin_id' => $admin_id, 'created' => date('Y-m-d H:i:s'));
                    $this->db_b->insert('ecoupon_key', $c_cate);
                } 
            }
            else 
            {
                $restaurants=$this->db_b->query('SELECT id FROM restaurant WHERE id_copy IS NOT NULL ') ->result_object();
                foreach($restaurants AS $le=>$el)
                {
                    $c_cate = array('id_restaurant' => $el->id, 'id_ecoupon' => $id, 'admin_id' => $admin_id, 'created' => date('Y-m-d H:i:s'));
                    $this->db_b->insert('ecoupon_key', $c_cate);
                } 
            }
            foreach ($zone as $key => $value)
            {
                $c_cate = array('id_coupon' => $id, 'id_zone' => $value['id'], 'admin_id' => $admin_id, 'created' => date('Y-m-d H:i:s'));
                $this->db_b->insert('ecoupon_zone_key', $c_cate);  
            }
            
        } 
        
    } 
}
